var app = getApp();

Page({
  data: {
    allKcal: 0,
    allFood: 0,
    isHistory: false,
    activityTypeId: 6, //优惠券类型
  },
  onLoad: function(options) {
    
  },
  selectDay2Data: function(event) {
    const that = this;
    const time = event.detail.time;
    console.error("selectDay2Data")
    app.xlogin.getUser(function(res){
      console.error("selectDay2Data")
      that.trainingRecord(time);
      that.historyTotal(time);
    });
  },
  selectDay2Sport: function (event) {
    const that = this;
    const time = event.detail.time;
    app.xlogin.getUser(function (res) {
      that.sportsData(time);
      that.getHeartRate(time);
      that.setData({
        sportTime: time
      })
    });
  },
  //跳转到柱状图
  navigator: function(event) {
    var index = event.currentTarget.dataset.index;
    var sportTime = this.data.sportTime;
    var url = app.xhx_route.dataDetail + "?index="+index+"&time="+sportTime;

    app.xlogin.getUser(function (res) {
      var myInfo = app.isNavigateToLogin();
      if (!myInfo) return;

      myInfo = app.isNavigateToBind();
      if (!myInfo) return;

      wx.navigateTo({
        url: url
      })
    })
  },
  //跳转到心率带
  toHeartRate : function(){
    wx.navigateTo({
      url: app.xhx_route.webview,
    })
  },
  //切换运动数据和历史健身
  toggleNav: function(event) {
    var that = this;
    var status = event.currentTarget.dataset.status;
    var isHistory = that.data.isHistory;
    if(status==isHistory) return false;
    that.setData({
      isHistory: status
    })
  },
  onShareAppMessage: function(res) {
    return {
      title: '',
      // path: app.xhx_route.login,
      success: function(res) {
        console.log(res)
      },
      fail: function(res) {
        // 转发失败
        console.log('转发失败')
      }
    }
  },
  sportsData,
  historyTotal,
  trainingRecord,
  getHeartRate,
})

// 获取全部运动，步行，力量健身，有氧运动，健身心率，睡眠记录数据
function sportsData(time) {
  var that = this;
  //获取用户code
  wx.login({
    success: function(res) {
      //获取用户加密运动数据
      wx.getWeRunData({
        complete(data) {
          var encryptedData = data.encryptedData || '';
          var iv = data.iv || '';
          var wxcode = res.code || '';

          //获取全部运动,步行,健身
          app.middleware.requestAjax({
            serAddr: app.serAddrs.sportDatas,
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            cancelToast: true,
            data: {
              date: time,
              wxcode: wxcode,
              iv: iv,
              encryptedData: encryptedData,
            },
            success: function(res) {
              console.log('全部运动数据', res);
              if (res.data.img) {
                that.setData({
                  head_bg: res.data.img
                })
              }
              var sleep_minute = 0;
              if (res.data.sleep.duration.toString().split(".").length == 2) {
                sleep_minute = res.data.sleep.duration.toString().split(".")[1];
              }
              var sleep_hour = res.data.sleep.duration.toString().split(".")[0];
              console.log('睡眠几小时', sleep_hour.toString().split(".")[0]);

              var noOxy = 0;
              var haveOxy = 0;
              if (res.data.NoO) {
                noOxy = (res.data.NoO.duration / 60).toFixed(1);
              }
              if (res.data.haveO) {
                haveOxy = (res.data.haveO.duration / 60).toFixed(1);
              }

              that.setData({
                res: res,
                data: res.data,
                step: res.data.runData.step,
                sleep_hour: sleep_hour,
                sleep_minute: sleep_minute,
                noOxy: noOxy,
                haveOxy: haveOxy
              })
            }
          })
        }
      })
    }
  })
}

function getHeartRate(time){
  var that = this; 
  app.middleware.requestAjax({
    serAddr: app.serAddrs.getAVGHeartRate,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    cancelToast: true,
    data: {
      currentDate: time,
    },
    success:function(res){
      console.log('获取心率的数据',res);
      that.setData({
        avgHeartRate: res.data.avgHeartRate || '',
      })
    }
  })
  
}

// 获取历史健身总数
function historyTotal(time) {
  var that = this;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.historyTotal,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    cancelToast: true,
    data: {
      type: 1
    },
    success: function(history) {
      console.log('历史健身的信息', history);
      that.setData({
        history: history.data
      })
    }
  })
}

// 获取历史健身当前查询天数据
function trainingRecord(time) {
  var that = this;
  var tempData = {};
  wx.request({
    url: app.Package.getPackage().openDomain + '/history/trainingRecord',
    header: {
      Authorization: 'Bearer ' + app.userInfo.plug_token
    },
    data: {
      date: time
    },
    success: function(res) {
      console.log('历史健身', res)
      var msg = res.data.msg;
      var status = res.data.code;
      var data = res.data;
      if (status == 200) { //成功
        var total = data.total || {};
        var tainingTime = total.tainingTime || 0;
        var trainingKcal = total.trainingKcal || 0;
        var trainingWeight = total.trainingWeight || 0;
        var list = data.selectDay || [];
        tempData.tainingTime = tainingTime;
        tempData.trainingKcal = trainingKcal;
        tempData.trainingWeight = trainingWeight;
        tempData.list = list.reverse();
        tempData.msg = '';
        console.log('历史健身数据', tempData);

        if (list.length == 0) tempData.msg = '暂无数据';

      } else {
        tempData.msg = msg;
      }
      that.setData({
        tempData: tempData
      })
    },
    fail: function() {
      tempData.msg = '获取失败';
      that.setData(tempData);
    }
  })
}